import 'package:flutter/material.dart';
import 'package:lib_uikit/widgets/gt_load_more_footer.dart';
import 'package:lib_uikit/widgets/gt_refresh_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///
/// @author Dayo
/// @created at 2023/10/8 16:06
/// @desc: 自定义刷新组件
///
class GTRefreshCustomView extends StatefulWidget {
  ///页面 必须是scrollerView的子类
  final Widget child;

  ///是否使用下拉刷新
  final bool enablePullDown;

  ///是否使用上拉加载
  final bool enablePullUp;

  ///刷新回调
  final Function(RefreshController refreshController)? onRefresh;

  ///加载回调
  final Function(RefreshController refreshController)? onLoading;

  final RefreshController? refreshController;
  final bool? initRefresh;

  const GTRefreshCustomView({
    Key? key,
    required this.child,
    this.enablePullDown = true,
    this.enablePullUp = true,
    this.onRefresh,
    this.onLoading,
    this.refreshController,
    this.initRefresh,
  }) : super(key: key);

  @override
  State createState() => _GTRefreshCustomViewState();
}

class _GTRefreshCustomViewState extends State<GTRefreshCustomView> with TickerProviderStateMixin {
  ///刷新控制器
  late final RefreshController _refreshController =
      widget.refreshController ?? RefreshController(initialRefresh: widget.initRefresh == true ? true : false);

  ///闲置加载状态
  bool idleLoadingState = true;

  ///闲置刷新状态
  bool idleRefreshState = true;

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  void _onRefresh() async {
    idleLoadingState ? await widget.onRefresh?.call(_refreshController) : _refreshController.refreshToIdle();
  }

  void _onLoading() async {
    idleRefreshState ? await widget.onLoading?.call(_refreshController) : _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      enablePullDown: widget.enablePullDown,
      enablePullUp: widget.enablePullUp,
      header: const GTRefreshHeader(),
      footer: const GTLoadMoreFooter(),
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: widget.child,
    );
    // return RefreshConfiguration(
    //     headerTriggerDistance: 60,
    //     //viewport不满一屏加载禁用
    //     // hideFooterWhenNotFull: true,
    //     //阻尼
    //     dragSpeedRatio: 0.7,
    //     //惯性触发
    //     enableBallisticLoad: true,
    //     //失败滑动重拾
    //     enableLoadingWhenFailed: true,
    //     child: SmartRefresher());
  }
}
